package com.Policing.Fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import androidx.annotation.Nullable;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import com.Policing.Ip_set.Ip_Set;
import com.Policing.Particulars;
import com.Policing.R;
import com.Policing.Since_case.Since_case;
import com.Policing.menu.SlideSideMenuExampleActivity;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by zq on 2017/1/13.
 */

public class Fragment1 extends Fragment {
	private ImageView imageView,rfid_Set;
	private TextView all_assets;//总资产
	private float all,in,idle,rest;
	private TextView in_assets;//在用资产
	private TextView idle_assets;//闲置资产
	private String url;
	private SlideSideMenuExampleActivity content;
	PieChart mChart;
	private String deptid;
	private LinearLayout unused;
	private LinearLayout in_use;
	private String getVersionUrl = "http://" + Ip_Set.IP + "/api/getVersionPDA";
	private String getAPK = "http://" + Ip_Set.IP + "/api/getAPKPDA";
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_second1, null);

	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		content = (SlideSideMenuExampleActivity) getActivity();
		SharedPreferences mm = content.getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
		deptid = mm.getString("id","");
		url = "http://"+ Ip_Set.IP+"/api/assetCountQuery";
        Log.i("ipipip",Ip_Set.IP);
		init();
		rfid_Set.setOnClickListener(v -> updateVersion());
		in_use.setOnClickListener(v -> {
			Intent intent = new Intent(getActivity(), Particulars.class);
			intent.putExtra("state","1");
			startActivity(intent);
		});

		unused.setOnClickListener(v -> {
			Intent intent = new Intent(getActivity(), Particulars.class);
			intent.putExtra("state","3");
			startActivity(intent);
		});

		setChart();
		setData();
		getpie();
	}


	private void init() {
		rfid_Set= (ImageView) content.findViewById(R.id.rfid_set);
		unused = (LinearLayout) getActivity().findViewById(R.id.unused);

		in_use = (LinearLayout) getActivity().findViewById(R.id.In_use);
		all_assets = (TextView) getActivity().findViewById(R.id.all_assets);
		in_assets = (TextView) getActivity().findViewById(R.id.in_assets);
		idle_assets = (TextView) getActivity().findViewById(R.id.idle_assets);
		imageView = (ImageView) getActivity().findViewById(R.id.opmenu);
		imageView.setOnClickListener(v -> {
			SlideSideMenuTransitionLayout mSlideSideMenu= (SlideSideMenuTransitionLayout)getActivity().findViewById(R.id.slide_side_menu);
			mSlideSideMenu.toggle();
		});
		load();
		mChart = (PieChart) getActivity().findViewById(R.id.pieChart);
	}

	private void load() {

		new Thread(){
			@Override
			public void run() {
				try {
					OkHttpClient client = new OkHttpClient();
					RequestBody requestBody = new FormBody.Builder()
							.add("id",deptid)
							.add("source", Since_case.set().getSource())
							.build();
					Request request = new Request.Builder()
							.url(url)
							.post(requestBody).build();
					Response response = client.newCall(request).execute();
					String responseData = response.body().string();
					Log.i("222",responseData);
					showResponse(responseData);//解析
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	private void showResponse(final String responseData) {
		content.runOnUiThread(() -> {
			try {
				JSONObject js  = new JSONObject(responseData);
				all_assets.setText(js.getString("asset"));
				idle_assets.setText(js.getString("unused"));
				in_assets.setText(js.getString("use"));

				all = Integer.parseInt(js.getString("asset"));
				idle = Integer.parseInt(js.getString("unused"));
				in = Integer.parseInt(js.getString("use"));
				rest = all-idle-in;
				setData();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		});
	}

	private void setChart() {
		mChart.setUsePercentValues(true);            //使用百分比显示
		//设置pieChart图表的描述
		mChart.setExtraOffsets(5, 10, 40, 10);        //设置pieChart图表上下左右的偏移，类似于外边距
		mChart.setDragDecelerationFrictionCoef(0.95f);//设置pieChart图表转动阻力摩擦系数[0,1]
		mChart.setRotationAngle(0);                   //设置pieChart图表起始角度
		mChart.setRotationEnabled(true);              //设置pieChart图表是否可以手动旋转
		mChart.setHighlightPerTapEnabled(true);       //设置piecahrt图表点击Item高亮是否可用
		mChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);// 设置pieChart图表展示动画效果

        // 设置 pieChart 图表Item文本属性
		mChart.setDrawEntryLabels(false);              //设置pieChart是否只显示饼图上百分比不显示文字（true：下面属性才有效果）
		mChart.setEntryLabelColor(Color.BLACK);       //设置pieChart图表文本字体颜色
		//设置pieChart图表文本字体样式
		mChart.setEntryLabelTextSize(12f);            //设置pieChart图表文本字体大小

        // 设置 pieChart 内部圆环属性
		mChart.setDrawHoleEnabled(true);              //是否显示PieChart内部圆环(true:下面属性才有意义)
		mChart.setHoleRadius(28f);                    //设置PieChart内部圆的半径(这里设置28.0f)
		mChart.setTransparentCircleRadius(31f);       //设置PieChart内部透明圆的半径(这里设置31.0f)
		mChart.setTransparentCircleColor(Color.BLACK);//设置PieChart内部透明圆与内部圆间距(31f-28f)填充颜色
		mChart.setTransparentCircleAlpha(50);         //设置PieChart内部透明圆与内部圆间距(31f-28f)透明度[0~255]数值越小越透明
		mChart.setHoleColor(Color.WHITE);             //设置PieChart内部圆的颜色
		mChart.setDrawCenterText(true);               //是否绘制PieChart内部中心文本（true：下面属性才有意义）
		//设置PieChart内部圆文字的字体样式
		mChart.setCenterText("资产");                 //设置PieChart内部圆文字的内容
		mChart.setCenterTextSize(10f);                //设置PieChart内部圆文字的大小
		mChart.setCenterTextColor(Color.BLACK);         //设置PieChart内部圆文字的颜色
		Description description = new Description();
		description.setText("");
		mChart.setDescription(description);
	}
	private void setData() {

        ArrayList<PieEntry> pieEntryList = new ArrayList<PieEntry>();
		ArrayList<Integer> colors = new ArrayList<Integer>();
		colors.add(Color.parseColor("#3794fc"));
		colors.add(Color.parseColor("#2dbe8d"));
		colors.add(Color.parseColor("#db585c"));
		colors.add(Color.parseColor("#f3ab11"));

		//饼图实体 PieEntry
		if (in>0){
			PieEntry CashBalance = new PieEntry(in/all, "在用资产 ");
			pieEntryList.add(CashBalance);
		}
		if (idle>0){
			PieEntry ConsumptionBalance = new PieEntry(idle/all, "闲置资产 ");
			pieEntryList.add(ConsumptionBalance);
		}
		if (rest>0){
			int j =(int)rest;
			PieEntry CashBalance2 = new PieEntry(rest/all, "其他 ");
			pieEntryList.add(CashBalance2);
		}

		//饼状图数据集 PieDataSet
		PieDataSet pieDataSet = new PieDataSet(pieEntryList, "");
		pieDataSet.setSliceSpace(3f);           //设置饼状Item之间的间隙
		pieDataSet.setSelectionShift(10f);      //设置饼状Item被选中时变化的距离
		pieDataSet.setColors(colors);           //为DataSet中的数据匹配上颜色集(饼图Item颜色)
		//最终数据 PieData
		PieData pieData = new PieData(pieDataSet);
		pieData.setDrawValues(true);            //设置是否显示数据实体(百分比,true:以下属性才有意义)
		pieData.setValueTextColor(Color.DKGRAY);  //设置所有DataSet内数据实体(百分比)的文本颜色
		pieData.setValueTextSize(12);          //设置所有DataSet内数据实体(百分比)的文本字体大小
		pieData.setValueFormatter(new PercentFormatter());//设置所有DataSet内数据实体(百分比)的文本字体格式
		mChart.setData(pieData);
		mChart.highlightValues(null);
		mChart.invalidate();                    //将图表重绘以显示设置的属性和数据

	}
	private void getpie(){
		// 获取pieCahrt图列
		Legend l = mChart.getLegend();
		l.setEnabled(true);                    //是否启用图列(true:下面属性才有意义)
		l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
		l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
		l.setOrientation(Legend.LegendOrientation.VERTICAL);
		l.setForm(Legend.LegendForm.DEFAULT); //设置图例的形状
		l.setFormSize(10);					  //设置图例的大小
		l.setFormToTextSpace(10f);			  //设置每个图例实体中标签和形状之间的间距
		l.setDrawInside(false);
		l.setWordWrapEnabled(true);			  //设置图列换行(注意使用影响性能,仅适用legend位于图表下面)
		l.setXEntrySpace(10f);				  //设置图例实体之间延X轴的间距(setOrientation = HORIZONTAL有效)
		l.setYEntrySpace(8f);				  //设置图例实体之间延Y轴的间距(setOrientation = VERTICAL 有效)
		l.setYOffset(0f);					  //设置比例块Y轴偏移量
		l.setTextSize(14f);					  //设置图例标签文本的大小
		l.setTextColor(Color.parseColor("#130c0e"));//设置图例标签文本的颜色
	}

 /**
 * 检查更新版本
 */
private void updateVersion() {
	// 获取当前版本号信息
	PackageInfo packInfo = null;
	try {
		packInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
	} catch (PackageManager.NameNotFoundException e) {
		e.printStackTrace();
	}
	assert packInfo != null;
	final int versionCode = packInfo.versionCode;
	//获取服务器里apk版本号
	OkHttpClient okHttpClient = new OkHttpClient();
	FormBody body = new FormBody.Builder()/*.add("source",Since_case.set().getSource())*/.build();
	Request request = new Request.Builder().url(getVersionUrl).post(body).build();
	Log.e("测试数据", getVersionUrl );
	try {
		okHttpClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
				e.printStackTrace();
				getActivity().runOnUiThread(() -> Toast.makeText(getContext(), "请检查网络", Toast.LENGTH_SHORT).show());

			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				if (response.isSuccessful()) {
					assert response.body() != null;
					InputStream inputStream = response.body().byteStream();
					//使用IO流读取数据
					String line = null;
					StringBuffer sb = new StringBuffer();
					BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
					while ((line = in.readLine()) != null) {
						sb.append(line);
					}
					inputStream.close();
					in.close();
					String versionInfo = sb.toString();
					final int updateVersion = Integer.parseInt(versionInfo.substring(versionInfo.indexOf(":") + 1));
					Log.i("测试1", "version: " + versionCode + "--updateVersion:" + updateVersion);
					//是否弹出有高版本时可以更新的提示框
					if (versionCode < updateVersion) {
						getActivity().runOnUiThread(() -> {
							final AlertDialog builder = new AlertDialog.Builder(getContext())
									.setTitle("更新提示")
									.setMessage("有新版本是否更新！")
									.setNegativeButton("否", (dialog, which) -> dialog.dismiss())
									.setPositiveButton("是", (dialog, which) -> {
										downloadAPK();
										dialog.dismiss();
									}).create();
							builder.setCanceledOnTouchOutside(false);
							builder.show();
						});
					}else {
						showToast("当前已是最新版本");
					}
				} else {
					Log.i("测试", "请求错误 ");
				}
			}
		});

	}catch (Exception e){e.printStackTrace();Log.i("测试", "请求错误 ");}

}
	private void showToast(final String msg){
		getActivity().runOnUiThread(() -> Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show());
	}

	/**
	 * 下载最新版apk
	 */
	private void downloadAPK() {
		//弹出进度提示框
		showDialog(getContext());
		OkHttpClient okHttpClient = new OkHttpClient();
		final FormBody body = new FormBody.Builder().build();
		final Request request = new Request.Builder().url(getAPK).post(body).addHeader("Accept-Encoding", "identity").build();
		okHttpClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
				showToast("请检查网络！");
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				if (response.isSuccessful()) {
					assert response.body() != null;
					final InputStream in = response.body().byteStream();
					//保存SD卡
					final File path = new File(Environment.getExternalStorageDirectory(), "Xt_slab_apk_pda");
					Log.e("测试", String.valueOf(path));
					if (!path.exists()) {
						path.mkdirs();
					}
					final File file = new File(path, "app.apk");
					if (file.exists()){
						file.delete();
					}
					if (!file.exists()) {
						file.createNewFile();
						FileOutputStream output = null;
						try {
							output = new FileOutputStream(file);
							int len = 0;
							byte[] buffer = new byte[1024];
							while ((len = in.read(buffer)) != -1) {
								output.write(buffer, 0, len);
								Log.i("测试", "len: " + len);
							}
							output.flush();
						} catch (IOException e) {
							Log.i("测试", "IOException: ");
						}
						assert output != null;
						output.close();
					}

					getActivity().runOnUiThread(() -> {
						progressDialog.cancel();
						// 安装apk
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						Uri data;
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
							// 通过FileProvider创建一个content类型的Uri
							data = FileProvider.getUriForFile(getContext(), "com.Assetspolling.provider", file);
							intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
						} else {
							data = Uri.fromFile(file);
						}
						intent.setDataAndType(data, "application/vnd.android.package-archive");
						startActivity(intent);
					});

				} else {
					Log.i("测试", "服务器异常！");
				}
			}
		});
	}
	private ProgressDialog progressDialog;
	private void showDialog(final Context context) {
		getActivity().runOnUiThread(() -> {
			progressDialog = new ProgressDialog(context);
			progressDialog.setTitle("正在下载中");
			progressDialog.setMessage("Loading...");
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.show();
		});
	}
}
